package com.cms.portal.controller.admin;

import com.cms.context.constant.Constants;
import com.cms.context.utils.UtilsRedis;
import com.cms.context.utils.UtilsShiro;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author laolang
 * @version 1.0.0
 * @ClassName CommonController
 */
@Controller
@Slf4j
public class CommonController {

    private static final String IMAGE_CAPTCHA_SUFIX="image_captcha";

    @Autowired
    private Producer captchaProducer;
    @Autowired
    private UtilsRedis utilsRedis;

    @GetMapping("captcha.do")
    public void getCaptcha( HttpServletResponse response) {

        String text = captchaProducer.createText();
        //根据用户的Id及生成图片的后缀的key  将值保存到redis中
        utilsRedis.set(UtilsShiro.getSession().getId() + Constants.IMAGE_CAPTCHA_SUFFIX,text,60L);
        //redisTemplate.opsForValue().set(UtilsShiro.getSession().getId()+ Constants.IMAGE_CAPTCHA_SUFFIX,text,60, TimeUnit.SECONDS);
        //设置图片格式
        response.setContentType("image/jsp");
        //禁止图片缓存
        response.setHeader("Pragma","no-cache");
        response.setHeader("Cache-Control","no-cache");
        response.setDateHeader("Expires",0);
        try(ServletOutputStream outputStream = response.getOutputStream()) {
            ImageIO.write(captchaProducer.createImage(text),"jpg",outputStream);

        } catch (IOException e) {
           log.error("验证码生成失败！");
        }

    }


}
